<template>
  <div class="avatar" :style="avatarStyle">
    <!-- <img class="rounded-full "  v-if="imgUrl" :src="imgUrl" alt=""> -->
    <span class="letter">{{ letter?.substr(0, 1) || "N" }}</span>
  </div>
</template>

<script setup>
import { defineProps, computed } from "vue";

const props = defineProps({
  letter: {
    type: String,
    required: true
  },
  letterColor: {
    type: String,
    default: "#FFFFFF" // White
  }
});

function getAvatarColor(name) {
  if (!name) return "#ccc";
  // 预定义一组好看的颜色
  const colors = [
    "#1abc9c",
    "#2ecc71",
    "#3498db",
    "#9b59b6",
    "#34495e",
    "#16a085",
    "#27ae60",
    "#2980b9",
    "#8e44ad",
    "#2c3e50",
    "#f1c40f",
    "#e67e22",
    "#e74c3c",
    "#95a5a6",
    "#f39c12",
    "#d35400",
    "#c0392b",
    "#7f8c8d"
  ];

  // 使用名字的 charCode 来确定颜色，这样同名用户会得到相同的颜色
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
}

const avatarStyle = computed(() => ({
  backgroundColor: getAvatarColor(props.letter),
  color: props.letterColor,
  borderRadius: "50%",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  width: "40px",
  height: "40px",
  fontSize: "16px",
  fontWeight: "bold"
}));
</script>

<style scoped lang="less">
.avatar {
  text-align: center;
}
.letter {
  user-select: none; /* Prevent text selection */
}
</style>
